package com.ybg.engine.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ybg.util.DateTimeUtil;
import com.ybg.util.LogUtil;
 /**
 * @author huang nc
 * @since  2017年3月31日
 */
public class UpdateStatusTask extends Task {

	private static boolean running = false;
	
	@Override
	public void run() throws Exception {
		 if (!enter()){
	            throw new RuntimeException("调度已经在进行中");
	        }
	        LogUtil.warn("teacher-course-stati...begin........");
	        long begin = new Date().getTime();

	        System.out.println("Do you see me？更改到勤状态调度");
	        updateStatus();
	        //TaskUtil.markProcess(jdbcTemplate, TaskName.TEACHER_COURSE, DateTimeUtil.getToday(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
	        long end = new Date().getTime();
	        LogUtil.info("本次任务用时 :" + (end - begin) / 1000 + "秒");
	        LogUtil.warn("teacher-course-stati...begin........");
	        leaving();
	}

	
	private void updateStatus() throws Exception {
		String updateStatusSql = "update ybg_b_sign set dqzt = 1 where dqzt = 6 ";
		String djjSql = "select djj from YBG_B_SIGN GROUP BY djj";
		String selectXksjSql = "SELECT xksj FROM YBG_B_SCHEDULE_COMMON_SKSJ where DJJ = ?";
		
		List<String> djjList = new ArrayList<String>();
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        long now = System.currentTimeMillis();
        String nowStr = format.format(now).substring(11, 16);
        long nowTime = 0;
        long dmsj = 0;
        String xksjStr = null ;
        
        try {
			nowTime = DateTimeUtil.SHORT_TIME.parse(nowStr).getTime();
			djjList = jdbcTemplate.queryForList(djjSql, String.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

        String djjString = null;
       for (String djjStr : djjList) {
    	   String [] strs = djjStr.split("-");
    	   int len = strs.length;
    	   if (len==1) {
    		    djjString = strs[0];
		   }else if (len==2) {
			   djjString = strs[1];
		   }else if (len==3) {
			   djjString = strs[2];
		}
           try {
			xksjStr = jdbcTemplate.queryForObject(selectXksjSql, String.class,djjString); //第几节课的下课时间
		} catch (Exception e) {
			e.printStackTrace();
		}
           dmsj = DateTimeUtil.SHORT_TIME.parse(xksjStr).getTime();
           
           long time = (nowTime - dmsj)/(1000*60);
           if (time>60) {
			jdbcTemplate.update(updateStatusSql);
		}
	}
		
	}

	private void leaving() {
		 running = false;
		
	}

	private boolean enter() {
		if(running){
            return false;
        }else{
            running = true;
            return true;
        }
	}

	@Override
	public String setSuccessResultMsg() {
		
		return "修改异常到勤状态成功";
	}

}
